package org.budo.support.log4j.appender;

import java.util.Properties;

import org.apache.log4j.helpers.LogLog;
import org.budo.support.java.net.util.JavaNetUtil;
import org.budo.support.lang.util.SystemUtil;

/**
 * @author lmw
 */
class BudoLog4jDailyRollingFileAppenderUtil {
    /**
     * @param file #{logFileRoot}/log/xxx-web/xxx-web.all.log
     */
    public static synchronized String fileWithExpression(String file) {
        Properties properties = SystemUtil.getEnvAndProperties();

        properties.put("budo.hostName", JavaNetUtil.getLocalHostName());

        String logFile = merge(file, properties);
        LogLog.warn(" DailyRollingFileAppender.setFile() file=" + file + " logFile=" + logFile);
        return logFile;
    }

    /**
     * 替换文件路径中的变量
     */
    public static String merge(String fileName, Properties properties) {
        int a = fileName.indexOf("#{");

        if (a < 0) {
            return fileName;
        }

        int b = fileName.indexOf('}', a);
        if (b <= a) {
            LogLog.error("DailyRollingFileAppender.setFile() fileName=" + fileName);
            return fileName;
        }

        String placeholder = fileName.substring(a + 2, b);
        String replacement = properties.getProperty(placeholder, "");
        String replacedStr = fileName.replace("#{" + placeholder + "}", replacement);
        return merge(replacedStr, properties);
    }
}